package com.ll.wechat.friends.fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import org.jivesoftware.smack.roster.RosterEntry;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import com.ll.wechat.R;
import com.ll.wechat.base.app.Constant;
import com.ll.wechat.base.fragment.BaseFragment;
import com.ll.wechat.base.net.NetCallBackListener;
import com.ll.wechat.base.net.NetUtil;
import com.ll.wechat.base.utils.widget.MyToast;
import com.ll.wechat.friends.activity.FriendsInfoActivity;
import com.ll.wechat.friends.adapter.FriendsListAdapter;
import com.ll.wechat.friends.utils.ABCList;
import com.ll.wechat.friends.utils.ABCList.onTouchABCListListener;
import com.ll.wechat.friends.utils.PinyinUtils;

/**
 * 通讯录列表
 * 
 * @ClassName: FriendsListFragment
 * @author yeliangliang
 * @date 2015-7-25 下午9:35:53
 */
public class FriendsListFragment extends BaseFragment implements OnItemClickListener {

	private ABCList abcView;// 字母提示
	private TextView tv_abc;
	// 好友列表
	private ListView mListView;
	private FriendsListAdapter mAdapter;
	private List<RosterEntry> rosterList;
	private HashMap<String, Integer> positionMap;
	private MyBroadCastReceiver receiver;

	// 响应变量
	@Override
	public int setRootViewId() {
		return R.layout.fragment_friends_list;
	}

	@Override
	protected void initView(View rootView) {
		abcView = (ABCList) rootView.findViewById(R.id.view_abc);
		abcView.setListener(ABCListener);
		tv_abc = (TextView) rootView.findViewById(R.id.tv_abc);
		mListView = (ListView) rootView.findViewById(R.id.list_friendsList);
		rosterList = new ArrayList<RosterEntry>();
		mAdapter = new FriendsListAdapter(getActivity(), rosterList);
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(this);
		mListView.setSelected(true);
	}

	@Override
	protected void initData() {
		// 请求好友列表
		requestRosterList();
	}

	/**
	 * 请求好友列表
	 * 
	 * @author yeliangliang
	 * @date 2015-7-27 下午2:06:43
	 * @version V1.0
	 * @return void
	 */
	private void requestRosterList() {
		NetUtil.requestRosterList(getActivity(), new NetCallBackListener() {
			@Override
			public void responseSuccess(int i, Object o) {
				handler.obtainMessage(i, o).sendToTarget();
			}

			@Override
			public void responseFailed(int i) {
				handler.obtainMessage(i).sendToTarget();
			}

			@Override
			public void responseError(int i) {
				handler.obtainMessage(i).sendToTarget();
			}

		});

	}

	// 字母提示框的回调
	private onTouchABCListListener ABCListener = new onTouchABCListListener() {
		@Override
		public void selectedDown(String letter) {
			// 显示
			tv_abc.setText(letter);
			tv_abc.setVisibility(View.VISIBLE);
			// 列表滚动至选定字母项
			if (positionMap != null) {
				if (positionMap.containsKey(letter)) {
					mListView.setSelection(positionMap.get(letter));
				}
			}
		}

		@Override
		public void selectedUp() {
			// 结束显示
			tv_abc.setVisibility(View.GONE);
		}
	};

	/**
	 * 滑动的时候隐藏字母边框
	 * 
	 * @author yeliangliang
	 * @date 2015-7-26 下午6:06:07
	 * @version V1.0
	 * @return void
	 */
	public void hideABC(int i) {
		switch (i) {
		case 0:// 滑动状态没有改变
			abcView.setVisibility(View.VISIBLE);
			break;
		case 1:// 正在滑动
				// 隐藏字母提示框
			abcView.setVisibility(View.GONE);
			abcView.setSelectedUp();
			break;
		case 2:// 滑动完毕
			abcView.setVisibility(View.VISIBLE);
			break;

		default:
			break;
		}
	}

	// 接收非UI线程的反馈
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case Constant.REQUEST_FAILD:
				MyToast.showToast(getActivity(), "获取好友列表失败");
				break;
			case Constant.REQUEST_SUCCESS:
				rosterList.clear();
				rosterList.addAll((List<RosterEntry>) msg.obj);
				sortList();
				mAdapter.myNotifyDataChange();
				positionMap = mAdapter.getPositionMap();
				break;
			default:
				break;
			}
		}

	};

	/**
	 * 按首字母排序 因为解析汉字首字母的逻辑比较麻烦也比较难 这里 利用pinyin4j.jar实现 开源库
	 * 
	 * @author yeliangliang
	 * @date 2015-7-27 下午5:12:32
	 * @version V1.0
	 * @return void
	 */
	@SuppressWarnings("unchecked")
	private void sortList() {
		PinyinComparator comp = new PinyinComparator();
		Collections.sort(rosterList, comp);
	}

	/**
	 * 按首字母排序 因为解析汉字首字母的逻辑比较麻烦也比较难 这里 利用pinyin4j.jar实现 开源库
	 * 
	 * @ClassName: PinyinComparator
	 * @author yeliangliang
	 * @date 2015-7-28 上午9:41:41
	 */
	public class PinyinComparator implements Comparator {

		@Override
		public int compare(Object o1, Object o2) {
			String str1 = PinyinUtils.getPingYin(((RosterEntry) o1).getName());
			String str2 = PinyinUtils.getPingYin(((RosterEntry) o2).getName());
			return str1.compareToIgnoreCase(str2);
		}

	}

	/**
	 * RosterEntry这个类没有实现Serializable接口,只能采用这种间接的方式传数据
	 */
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// 点击Item跳转到好友信息页面
		Bundle bundle = new Bundle();
		bundle.putString("name", rosterList.get(position).getName());
		bundle.putString("passName", rosterList.get(position).getUser());
		showActivity(getActivity(), FriendsInfoActivity.class, bundle);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (receiver != null) {
			getActivity().unregisterReceiver(receiver);
		}
	}

	@Override
	public void onStart() {
		super.onStart();
		if (receiver == null) {
			receiver = new MyBroadCastReceiver();
		}
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(Constant.RECIVER_DELETE_FRIENDS);
		getActivity().registerReceiver(receiver, intentFilter);
	}

	private class MyBroadCastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			requestRosterList();
		}

	}
}
